import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_comment.dart';
import 'package:ceramics/model/ab_like.dart';
import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/model/ab_video.dart';
import 'package:ceramics/model/ab_works.dart';
import 'package:ceramics/pages/login/ab_login_page.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:ceramics/util/ab_alert.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_loading.dart';
import 'package:ceramics/util/ab_log_util.dart';
import 'package:ceramics/widgets/ab_elevate_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:simple_app_cache_manager/simple_app_cache_manager.dart';

class ABSystemSettingPage extends StatefulWidget {
  const ABSystemSettingPage({super.key});

  @override
  State<ABSystemSettingPage> createState() => _ABSystemSettingPageState();
}

class _ABSystemSettingPageState extends State<ABSystemSettingPage> {

  var _cacheSize = '0.0KB';
  var _version = '1.0.0';
  var cacheManager = SimpleAppCacheManager();

  @override
  void initState() {
    super.initState();
    _getDatas();
  }

  _getDatas() async {
    var size = await cacheManager.getTotalCacheSize();
    var pkg = await PackageInfo.fromPlatform();
    var version = pkg.version;
    setState(() {
      _cacheSize = size;
      _version = version;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: const Text('System Setting'),
      ),
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/ceramics_39.webp"),
            fit: BoxFit.cover,
          ),
        ),
        width: double.infinity,
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              20.toVerticalBox,
              // const Text('清除缓存', style: ABStyles.tsNormalBlack15),
              Container(
                color: Colors.transparent,
                child: ListTile(
                  onTap: _clearCache,
                  title: Text('Clear Cache'.tr, style: ABStyles.tsDarkBlack17Bold),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(_cacheSize, style: ABStyles.tsNormalBlack15),
                      10.toHorizontalBox,
                      const Icon(Icons.arrow_forward_ios, size: 15),
                    ]
                  ),
                ),
              ),
              1.toVerticalBox,
              Container(
                color: Colors.transparent,
                child: ListTile(
                  onTap: (){},
                  title: const Text('Version', style: ABStyles.tsDarkBlack17Bold),
                  trailing: Text(_version, style: ABStyles.tsNormalBlack15),
                ),
              ),
              Container(
                color: Colors.transparent,
                child: ListTile(
                  onTap: () {
                    showAlert(
                      title: 'Delete Account'.tr,
                      message: 'Are you sure you want to delete your account?  This action cannot be undone. Please be careful.'.tr,
                      cancelText: 'Cancel'.tr,
                      onOk:_deleteAccount);
                  },
                  title: const Text('Delete Account', style: ABStyles.tsDarkBlack17Red),
                  trailing: const Icon(Icons.arrow_forward_ios, size: 15),
                ),
              ),
              80.toVerticalBox,
              ABElevateButton(
                child: const Text('Logout', style: ABStyles.tsWhite20R),
                onPressed: () {
                  showAlert(
                      title: 'Logout'.tr,
                      message: 'Are you sure you want to logout?'.tr,
                      cancelText: 'Cancel'.tr,
                      onOk: _logout);
                }
              ).size(width: 200),
            ],
          ),
        ),
      )
    );
  }

  void _clearCache() async {
    loading(msg: 'Clearing Cache...');
    cacheManager.clearCache();
    await Future.delayed(const Duration(seconds: 1));
    setState(() {
      _cacheSize = '0.0KB';
    });
    toast('Clear Cache Success');
  }

  _deleteAccount() async {
    loading(msg: 'deleteaccount');
    await api.deleteAccount();
    await ABWorks.deleteWorksWithUserId(ABSingleton.user?.userId ?? '');
    await ABLike.deleteLikesWithUserId(ABSingleton.user?.userId ?? '');
    await ABComment.deleteCommentsWithUserId(ABSingleton.user?.userId ?? '');
    await ABVideo.deleteVideosWithUserId(ABSingleton.user?.userId ?? '');
    await ABSingleton.removeOAuth();
    Get.offAll(() => const ABLoginPage());
  }

  _logout() async {
    LogPvManger.stat(page: 'logout');
    await api.logout();
    await ABSingleton.removeOAuth();
    Get.offAll(() => const ABLoginPage());
  }
}
